package com.tinem.platform.web.gateway.filter;

import com.tinem.platform.module.pojo.vo.error.UserException;
import com.tinem.platform.module.starter.sdk.MessageCode;
import com.tinem.platform.web.gateway.util.GatewayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * @author fengzhihao
 * @version v1
 * @program: platform
 * @className ChannelScopeGatewayFilterFactory
 * @description 客户端时间参数验证
 * @site 
 * @company 
 * @create 2020-07-03 12:26
 */
@Slf4j
@Component
public class TimeoutGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {
    int durationMin = 5;
    long duration = Duration.ofMinutes(durationMin).getSeconds()*1000;
    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            Long timestamp = GatewayUtil.getReqTimestamp(exchange);
            // 请求发起时间在当前时间之后。
            Long sysTime = System.currentTimeMillis();
            if(timestamp > sysTime){
                log.warn("client time error; req time > sys time;({}):({})",timestamp,sysTime);
            }
            if(sysTime - timestamp > duration){
                log.warn("The system time and client time exceed {} minutes;({}) - ({}) = {}",durationMin,sysTime,timestamp,sysTime-timestamp);
                throw new UserException(MessageCode.ERROR_COMMONS_CLIENT_TIME,timestamp,sysTime);
            }
            return chain.filter(exchange);
        };
    }
}
